package com.example.c5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;


/**
 * @author Jonathan
 * 2021/6/1 20:54
 */
public class EventLoopServer {

    public static void main(String[] args) {
        try {
            new ServerBootstrap()
                    // boss and worker
                    .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    // bytebuffer
                                    System.out.println(msg);
                                    ByteBuf msg1 = null;
                                    try {
                                        msg1 = (ByteBuf) msg;
                                        System.out.println(msg1.toString(Charset.defaultCharset()));
                                        super.channelRead(ctx, msg);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    }).bind(8080);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
